# -*- coding:utf-8 -*-

import os
import time
import threading
import subprocess
import config.glob.config as global_cfg
from utils.log_utils import log_debug

"""
tensorboard 工具
"""


def oepn_in_browser(url='http://localhost:6006'):
    """
    浏览器打开网址
    :param url:
    :return:
    """
    cmd = '"' + global_cfg.BROWSER_DIR + '" ' + url
    os.system(cmd)


def cmd_run_tensorboard(log_dir):
    """
    cmd打开tensorboard
    :param log_dir: 日志路径
    :return:
    """
    command = 'tensorboard --logdir=' + log_dir
    process = subprocess.Popen(
        command, shell=True,
        stdin=subprocess.PIPE,
        stdout=subprocess.PIPE,
        stderr=subprocess.PIPE
    )
    # todo 最好获取句柄url,输入给oepn_in_browser
    while True:
        if not process.poll():
            time.sleep(5)
            process.kill()
        else:
            oepn_in_browser()
            break


class DefaultThread (threading.Thread):
    """
    自定义线程
    """
    def __init__(self, thread_id, name, log_dir):
        threading.Thread.__init__(self)
        self.threadID = thread_id
        self.name = name
        self.log_dir = log_dir

    def run(self):
        log_debug("tensorboarad is opening soon", fore='dy')
        cmd_run_tensorboard(self.log_dir)


def kill_tensorboard():
    """
    清除所有tensorboard进程
    :return:
    """
    process = subprocess.Popen(
        "taskkill /F /IM tensorboard.exe", shell=True,
        stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
    cmd_log = str(process.stdout.read())
    process.wait()
    log_debug('close all tensorbord.exe, {}'.format(cmd_log), fore='dy')


def run_tensorboard(log_dir):
    """
    运行tensorboard 整体流程
    :param log_dir: 日志路径
    :return:
    """
    # kill已经打开的所有tensorboard
    kill_tensorboard()
    # 创建新线程
    thread1 = DefaultThread(1, "TensorboardThread", log_dir)
    # 开启新线程
    thread1.start()
    # thread1.join()
